########################################################################
#  Searx-qt - Lightweight desktop application for SearX.
#  Copyright (C) 2020  CYBERDEViL
#
#  This file is part of Searx-qt.
#
#  Searx-qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################

import random

from PyQt5.QtCore import QObject, pyqtSignal

from searxqt.core.instances import Stats2


class SettingsModel(QObject):
    changed = pyqtSignal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent=parent)

        self._requests = RequestSettingsModel()
        self._stats2 = None

        self._requests.changed.connect(self.changed)

    def loadSettings(self, data, stats2=True):
        self.requests.data = data.get('requests', {})

        if self._stats2:
            self._stats2.deleteLater()
            self._stats2 = None

        if stats2:
            self._stats2 = SearxStats2Model()
            stats2Data = data.get('stats2', {})
            self.stats2.loadSettings(stats2Data)

    def saveSettings(self):
        if self._stats2:
            return {
                'requests': self.requests.data,
                'stats2': self.stats2.saveSettings()
            }
        return {
            'requests': self.requests.data,
        }

    @property
    def requests(self): return self._requests

    @property
    def stats2(self): return self._stats2


class SearxStats2Model(QObject):
    changed = pyqtSignal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent=parent)
        self._backupUrl = Stats2.URL

    def loadSettings(self, data):
        self.url = data.get('url', self._backupUrl)

    def saveSettings(self):
        return {
            'url': self.url
        }

    def reset(self):
        self.url = self._backupUrl

    @property
    def url(self):
        return Stats2.URL

    @url.setter
    def url(self, url):
        Stats2.URL = url
        self.changed.emit()


class RequestSettingsModel(QObject):
    changed = pyqtSignal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent=parent)
        self._kwargs = {
            'verify': True,
            'timeout': 10,
        }

        self._randomUserAgent = True
        self._useragents = ['searx-qt']

    def __changed(self): self.changed.emit()

    @property
    def data(self):
        return {
            'useragents': self._useragents,
            'randomUserAgent': self._randomUserAgent,
            'kwargs': self._kwargs
        }

    @data.setter
    def data(self, data):
        self._useragents = data.get('useragents', ['searx-qt'])
        self._randomUserAgent = data.get('randomUserAgent', True)

        kwargs = data.get('kwargs', {})
        self._kwargs.update({'verify': kwargs.get('verify', True)})
        self._kwargs.update({'timeout': kwargs.get('timeout', 10)})
        self._kwargs.update({'proxies': kwargs.get('proxies', {})})

    @property
    def kwargs(self):
        """ Returns kwargs to be passed to requests.get
        """
        kwargs = self._kwargs.copy()
        kwargs.update({'headers': self.headers})
        return kwargs

    @kwargs.setter
    def kwargs(self, kwargs):
        self._kwargs = kwargs

    @property
    def verify(self): return self._kwargs['verify']

    @verify.setter
    def verify(self, state):
        self._kwargs['verify'] = state
        self.__changed()

    @property
    def timeout(self): return self._kwargs['timeout']

    @timeout.setter
    def timeout(self, state):
        self._kwargs['timeout'] = state
        self.__changed()

    @property
    def proxies(self): return self._kwargs.get('proxies', {})

    @proxies.setter
    def proxies(self, data):
        self._kwargs.update({'proxies': data})
        self.__changed()

    @property
    def headers(self):
        headers = {}
        if self.useragent:
            headers.update({'user-agent': self.useragent})
        return headers

    @property
    def useragent(self):
        if not self._useragents:
            return ""

        if len(self._useragents) == 1 or not self._randomUserAgent:
            return self._useragents[0]

        return random.choice(self._useragents)

    @property
    def useragents(self):
        return self._useragents

    @useragents.setter
    def useragents(self, strList):
        """
        @param strList: A string with user-agents, separated by a new line.
                        May be empty.
        @type strList: str
        """
        self._useragents = strList
        self.__changed()

    @property
    def randomUserAgent(self): return self._randomUserAgent

    @randomUserAgent.setter
    def randomUserAgent(self, state):
        """
        @param state: True to select random user-agent for each request
                      If False it will select the first user-agent. When
                      the user-agents list is empty the send string will
                      be also empty.
        @type state: bool
        """
        self._randomUserAgent = state
        self.__changed()
